<?php
class ProductCategoryService extends My_Service
{   
    protected function check()
    {	
    	//validate CategoryName
		$nameVald = new Zend_Validate_StringLength(1, 50);
		if(!$nameVald->isValid($_POST['categoryName']))
		{
			$this->_errorList["categoryName"] = My_Message::get("S002|Category name|1|50");
		}
		
		//validate Description
		$descVald = new Zend_Validate_StringLength(1, 255);
		if(!$descVald->isValid($_POST['description']))
		{
			$this->_errorList["description"] = My_Message::get("S002|Description|1|255");
		}
		
    	//validate image
		if(!empty($_FILES['imageURL']['name']))
		{
			$adapter = new Zend_File_Transfer_Adapter_Http();

			/*$adapter->addValidator('IsImage', false);
			if(!$adapter->isValid())
			{
				$this->_errorList["imageURL"] = My_Message::get("S004");
				return false;
			}*/

			$uploadDir = PRODUCT_IMG_UPLOAD_PATH;
			if(!is_readable($uploadDir))
			{
				$this->_errorList["imageURL"] = My_Message::get("S005|Image");
				return false;
			}
			
			$adapter->setDestination ($uploadDir);
			if (! $adapter->receive ()) {
				$this->_errorList["imageURL"] = My_Message::get("S005|Image");
				return false;
			}
		}
		
		if(empty($this->_errorList) == false)
		{
			return false;
		}
		return true;
    }
    
	public function bind()
	{
		$category = new ProductCategoryDTO( );
		if(!empty($_POST['categoryId']))//case edit
		{
			$category = $this->load($_POST['categoryId']);
		}
		else//case insert
		{
			$category->languageId = My_Translate::getLanguage();
		}
		
		$category->categoryName = $_POST['categoryName'];
		$category->description = $_POST['description'];
		
		if (! empty ( $_FILES ['imageURL']['name'] )) 
		{
			if(!empty($_POST['categoryId']))//case edit, remove old images
			{
				$uploadDir = PRODUCT_IMG_UPLOAD_PATH;
				$imgFile = $uploadDir.$category->imageURL;
				@unlink($imgFile);
			}
			$category->imageURL = basename ( $_FILES ['imageURL'] ['name'] );
		}
		
		return $category;
	}
    
    public function store()
    {
    	//check input data
    	if(!$this->check()){
			return false;
    	}
    	
    	//bind data
    	$category = $this->bind();
    	
    	//save data
    	$this->save($category);
    	return true;
    }
    
    
}
?>